import { postAuth } from "../http";
import { AGENT_BACKEND_API_KEY } from "../auth";
import { ChatGPTConfig, defaultChatGPTConfig } from "./config";

// 定义请求体的接口
interface ChatCompletionRequest {
    model: string;
    messages: {
        role: "system" | "user" | "assistant";
        content: string;
    }[];
}

// 定义响应体的接口
interface ChatCompletionResponse {
    id: string;
    object: string;
    created: number;
    model: string;
    system_fingerprint: string;
    choices: {
        index: number;
        message: {
            role: "assistant";
            content: string;
        };
        logprobs: null;
        finish_reason: string;
    }[];
    usage: {
        prompt_tokens: number;
        completion_tokens: number;
        total_tokens: number;
        completion_tokens_details: {
            reasoning_tokens: number;
        };
    };
}

/**
 * 获取聊天完成响应
 * @param request 请求体
 * @returns
 */
export async function getChatCompletion(
    request: ChatCompletionRequest,
    apiKey: string,
    modelConfig: ChatGPTConfig
): Promise<ChatCompletionResponse> {
    const key = apiKey ?? AGENT_BACKEND_API_KEY;
    if (!key) {
        throw new Error("API key is missing");
    }

    const config = { ...defaultChatGPTConfig, ...modelConfig };

    const requestBody = {
        ...config,
        model: request.model,
        messages: request.messages
    };

    try {
        const response = await postAuth<ChatCompletionResponse>(
            "https://api.openai.com/v1/chat/completions",
            requestBody,
            key
        );

        if (response.status === 200) {
            // 返回助手的回复内容
            return response.data;
        } else {
            console.error(`Unexpected response status: ${response.status}`);
            throw new Error("Failed to get chat completion");
        }
    } catch (error) {
        console.error("Error in getting chat completion:", error);
        throw error;
    }
}
